from typing import List, Optional
from storage import Storage
from task import Task


class TaskManager:
    def __init__(self):
        self.storage = Storage()
        self.data = self.storage.load_data()

    def add_task(self, name: str) -> int:
        """添加新任务并返回任务ID"""
        task_id = self.data["next_id"]
        task = Task(task_id, name)

        self.data["tasks"].append(task.to_dict())
        self.data["next_id"] += 1
        self.storage.save_data(self.data)

        return task_id

    def list_tasks(self) -> List[Task]:
        """返回所有任务列表"""
        return [Task.from_dict(task_data) for task_data in self.data["tasks"]]

    def remove_task(self, task_id: int) -> bool:
        """删除指定ID的任务，返回是否成功"""
        initial_length = len(self.data["tasks"])
        self.data["tasks"] = [
            task_data for task_data in self.data["tasks"] if task_data["id"] != task_id
        ]

        if len(self.data["tasks"]) < initial_length:
            self.storage.save_data(self.data)
            return True
        return False

    def get_task(self, task_id: int) -> Optional[Task]:
        """根据ID获取任务"""
        for task_data in self.data["tasks"]:
            if task_data["id"] == task_id:
                return Task.from_dict(task_data)
        return None

    def update_task(self, task: Task) -> bool:
        """更新任务数据"""
        for i, task_data in enumerate(self.data["tasks"]):
            if task_data["id"] == task.id:
                self.data["tasks"][i] = task.to_dict()
                self.storage.save_data(self.data)
                return True
        return False

    def increment_pomodoro_count(self, task_id: int) -> bool:
        """增加任务的番茄钟计数，返回是否成功"""
        task = self.get_task(task_id)
        if task:
            task.increment_pomodoro()
            return self.update_task(task)
        return False
